package com.zhaoyd.uaademo.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhaoyd.uaademo.core.SpringContextUtils;

/**
 * json-bean convert util
 * @author zhaoyd
 * @date 2020-10-31
 */
public class JsonBeanConvertUtils {

    private volatile static ObjectMapper objectMapper;

    public static <T> T JsonToBean(String json,Class<T> clazz) throws JsonProcessingException {
        ObjectMapper objectMapper = getObjectMapper();
        T bean = (T)objectMapper.readValue(json, clazz);
        return bean;
    }

    public static <T> String beanToJson(T bean) throws JsonProcessingException {
        ObjectMapper objectMapper = getObjectMapper();
        String json = objectMapper.writeValueAsString(bean);

        return json;
    }

    /**
     * 获取objectMapper的单例，与controller返回json一致
     * @return
     */
    private static ObjectMapper getObjectMapper(){
        if(objectMapper == null){
            synchronized (JsonBeanConvertUtils.class){
                if(objectMapper == null){
                    objectMapper = SpringContextUtils.getBean(ObjectMapper.class);
                }
            }
        }
        return objectMapper;
    }
}
